<?php

namespace app\common\model\user;

use app\common\model\Acct;
use app\common\model\Acctmoneylog;
use app\common\model\Area;
use app\common\model\Config;
use app\common\model\shop\Order;
use app\common\model\Systemconfig;
use app\common\model\User;
use think\Model;
use think\Db;
use think\Log;
use traits\model\SoftDelete;

class Commission extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'user_commission';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'createtime_text'

    ];


    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }




    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function sourceuser()
    {
        return $this->belongsTo('app\common\model\User', 'source_user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    protected static function init()
    {
        self::event('before_insert', function ($obj) {
            $obj->createdate = date('Y-m-d');
            $obj->createmonth = date('Ym');
        });
    }

    /**
     * 佣金结算
     */
    public static function addCommission($order)
    {
        Db::startTrans();
        try {
            $user = $order->user;
            if ($user && $user->parent_id) {
                $puser = User::where('id', $user->parent_id)->find();
                if ($puser) {
                    if ($order->only_fx_price) {
                        $fx_money = 0;
                        foreach ($order->ordergoods as $key => $v) {
                            $fx_money += $v->pay_price * $v->total * ($v->goods_info_json['fx_rate'] ?? 0) / 100;
                        }
                        if ($fx_money >= 0.01) {
                            $data = [
                                'user_id' => $puser->id,
                                'order_no' => $order->order_no,
                                'money' => $fx_money,
                                'msg' => '【' . $order->user->nickname . '#' . $order->user->id . '】直推下单',
                                'type' => 'only_fx',
                                'status' => '1',
                                'source_user_id' => $order->user_id,
                                'source_price' => $order->total_fee,
                                'acct_id' => $puser->acct_id
                            ];
                            self::create($data);
                        }
                    }

                    $team_revenue = config('site.team_revenue') ?? 0;
                    $team_revenue = $puser->fx_rate > 0 ? $puser->fx_rate : $team_revenue ?? 0;
                    $team = bcdiv($team_revenue, 100, 2);
                    $money = bcmul($order->total_fee - $order->only_fx_price, $team, 2);

                    if ($money >= 0.01) {
                        $data = [
                            'user_id' => $puser->id,
                            'order_no' => $order->order_no,
                            'money' => $money,
                            'msg' => '【' . $order->user->nickname . '#' . $order->user->id . '】下单',
                            'type' => 'fx',
                            'status' => '1',
                            'source_user_id' => $order->user_id,
                            'source_price' => $order->total_fee,
                            'acct_id' => $puser->acct_id
                        ];
                        if (!self::get($data)) {
                            self::create($data);
                        }
                    }
                }
            }
            self::addChannelCommission($order);
            self::addLevelCommission($order);
            self::addDevCommission($order);
            self::addAgentCommission($order);
            // self::pushChannelCommission($order);
            //code...
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::write('佣金结算错误,id:' . var_export($e), 'error');
        }
    }

    /**
     * 等级佣金结算
     */
    public static function addLevelCommission($order)
    {
        $money = $order->total_fee - $order->only_fx_price;
        $all_level = Level::order('last_month_ach asc')->select();
        if (!$order->user) {
            return;
        }
        $level_id = $order->user->level_id;
        if ($level_id) {
            $level = Level::get($level_id);
            $next_level = Level::getNextLevel($all_level, $level);
        } else {
            $next_level = Level::getNextLevel($all_level);
        }
        if ($next_level) {
            bcscale(2);
            $all_user = User::where('level_id', $next_level->id)->select();
            if (!$all_user) {
                return;
            }
            $per_money =  bcdiv(bcdiv(bcmul($money, $next_level->commission_rate), 100), count($all_user));
            if ($per_money >= 0.01) {
                $insert_data = [];
                foreach ($all_user as $u) {
                    array_push($insert_data, [
                        'user_id' => $u->id,
                        'order_no' => $order->order_no,
                        'money' => $per_money,
                        'msg' => '【' . $order->user->nickname . '#' . $order->user->id . '】下单等级奖励',
                        'type' => 'level',
                        'status' => '1',
                        'source_user_id' => $order->user_id,
                        'source_price' => $order->total_fee,
                        'acct_id' => $u->acct_id
                    ]);
                }

                $commission = new self;
                $commission->saveAll($insert_data);
            }
        }
    }
    /**
     * 差价佣金结算
     */
    public static function addDevCommission1($order)
    {

        if ($order['type'] == 0) {
            $money = bcsub($order->pay_fee - $order->send_fee, $order->total_fee, 2);
        } else {
            $money = bcsub($order->pay_fee, $order->total_fee, 2);
        }

        Db::startTrans();
        try {
            $info = self::get(
                [
                    'user_id' => $order->user_id,
                    'order_no' => $order->order_no,
                    'msg' => '订单差价',
                    'type' => 'dev',
                    'status' => '1',
                    'source_user_id' => $order->user_id,
                    'source_price' => $order->total_fee,
                    'acct_id' => $order->acct_id
                ]
            );
            if ($info && $money != $info['money']) {
                $price = $info['money'];
                if ($money <= 0) {
                    $info->delete();
                } else {
                    $info->money = $money;
                    $info->save();
                }
                User::where('id', $order->user_id)->setDec('commission', $price);
                User::where('id', $order->user_id)->setInc('commission', $money);
            }
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            exception($th->getMessage());
            Log::error(var_export($th, true));
        }
    }
    /**
     * 子平台收益结算
     */
    public static function addAcctCommission($order)
    {
        $money = $order->total_fee - $order->original_price;
        if ($money >= 0.01) {
            // $data = [
            //     'user_id' => $order->user_id,
            //     'order_no' => $order->order_no,
            //     'money' => $money,
            //     'msg' => '子平台收益',
            //     'type' => 'dev',
            //     'status' => '1',
            //     'source_user_id' => $order->user_id,
            //     'source_price' => $order->total_fee,
            //     'acct_id' => $order->acct_id
            // ];
            $acct = Acct::get($order->acct_id);
            Acctmoneylog::money($money, $acct->admin_id, '子平台收益', '', $order->order_no);
            // self::create($data);
        }
    }
    /**
     * 差价佣金结算
     */
    public static function addDevCommission($order)
    {
        if ($order['type'] == 0) {
            $money = $order->pay_fee - $order->total_fee - $order->send_fee;
        } else {
            $money = $order->pay_fee - $order->total_fee;
        }
        if ($money >= 0.01) {
            $data = [
                'user_id' => $order->user_id,
                'order_no' => $order->order_no,
                'money' => $money,
                'msg' => '订单差价',
                'type' => 'dev',
                'status' => '1',
                'source_user_id' => $order->user_id,
                'source_price' => $order->total_fee,
                'acct_id' => $order->acct_id
            ];

            self::create($data);
        }
    }
    /**
     * 渠道商佣金结算
     */

    // public static function addChannelCommission($order)
    // {
    //     $user = User::get($order->user_id);
    //     if (!$user) {
    //         return;
    //     }
    //     // $channel_commission =  Systemconfig::where(['acct_id' => $order->acct_id, 'name' => 'channel_commission'])->value('value') ?? 0;

    //     if ($user->is_channel == 1) {
    //         $channel_id = $user->id;
    //     } else {
    //         // $channel_id = $user->channel;
    //         $channel_id = self::getChannel($user->parent_id);
    //     }


    //     if (!$channel_id) {
    //         return;
    //     }
    //     $channeluser = User::where('id', $channel_id)->where('is_channel', 1)->find();
    //     if (!$channeluser) {
    //         return;
    //     }
    //     $channel_commission =  Channel::where('id',$channeluser->channel_level)->value('commission_rate');
    //     if ($channel_commission <= 0) {
    //         return;
    //     }
    //     $channel = bcdiv($channel_commission, 100, 2);
    //     if ($channel <= 0) {
    //         return;
    //     }

    //     $money = bcmul($order->total_fee - $order->only_fx_price, $channel, 2);
    //     if ($money <= 0) {
    //         return;
    //     }
    //     $data = [
    //         'user_id' => $channel_id,
    //         'order_no' => $order->order_no,
    //         'money' => $money,
    //         'msg' => '渠道商佣金',
    //         'type' => 'channel',
    //         'status' => '1',
    //         'source_user_id' => $order->user_id,
    //         'source_price' => $order->total_fee,
    //         'acct_id' => $order->acct_id
    //     ];
    //     self::create($data);
    //     $first = self::getChannel($channeluser->parent_id);
    //     if (!$first) {
    //         return;
    //     }
    //     $firstuser = User::get($first);
    //     if (!$firstuser || $firstuser['channel_level'] < 2) {
    //         return;
    //     }
    //     $commission_rate = db('user_channel')->where('id', $firstuser['channel_level'])->value('commission_rate');
    //     if ($commission_rate <= 0) {
    //         return;
    //     }
    //     $proportion = $commission_rate / 100;
    //     if ($proportion <= 0) {
    //         return;
    //     }
    //     $first_money = bcmul($order->total_fee - $order->only_fx_price, $proportion, 2);
    //     if ($first_money <= 0) {
    //         return;
    //     }
    //     $data = [
    //         'user_id' => $first,
    //         'order_no' => $order->order_no,
    //         'money' => $first_money,
    //         'msg' => '一级管理佣金',
    //         'type' => 'first',
    //         'status' => '1',
    //         'source_user_id' => $order->user_id,
    //         'source_price' => $order->total_fee - $order->only_fx_price,
    //         'acct_id' => $order->acct_id
    //     ];
    //     self::create($data);
    //     // $firstuser = User::get($first);
    //     // if (!$firstuser) {
    //     //     return;
    //     // }
    //     // $two = $firstuser->parent_id;
    //     // if (!$two) {
    //     //     return;
    //     // }

    //     // $two_rate = config('site.two') ?? 0;
    //     // if ($two_rate <= 0) {
    //     //     return;
    //     // }
    //     // $two_proportion = $two_rate / 100;
    //     // if ($two_proportion <= 0) {
    //     //     return;
    //     // }
    //     // $two_money = bcmul($order->total_fee - $order->only_fx_price, $two_proportion, 2);
    //     // if ($two_money <= 0) {
    //     //     return;
    //     // }
    //     // $data = [
    //     //     'user_id' => $two,
    //     //     'order_no' => $order->order_no,
    //     //     'money' => $two_money,
    //     //     'msg' => '二级管理佣金',
    //     //     'type' => 'two',
    //     //     'status' => '1',
    //     //     'source_user_id' => $order->user_id,
    //     //     'source_price' => $order->total_fee - $order->only_fx_price,
    //     //     'acct_id' => $order->acct_id
    //     // ];
    //     // self::create($data);
    // }
    public static function addChannelCommission($order)
    {
        $user = User::get($order->user_id);
        if (!$user) {
            return;
        }
        if ($user->is_channel == 1) {
            $channel_id = $user->id;
        } else {
            // $channel_id = $user->channel;
            $channel_id = self::getChannel($user->parent_id);
        }
        if (!$channel_id) {
            return;
        }
        $channeluser = User::where('id', $channel_id)->where('is_channel', 1)->find();
        if (!$channeluser) {
            return;
        }
        // $channel_commission =  Systemconfig::where(['acct_id' => $order->acct_id, 'name' => 'channel_commission'])->value('value') ?? 0;
        $channel_commission =  Channel::where('id', $channeluser->channel_level)->value('commission_rate');
        if ($channel_commission <= 0) {
            return;
        }
        $channel = bcdiv($channel_commission, 100, 2);
        if ($channel <= 0) {
            return;
        }
        $money = bcmul($order->total_fee - $order->only_fx_price, $channel, 2);
        if ($money <= 0) {
            return;
        }
        $data = [
            'user_id' => $channel_id,
            'order_no' => $order->order_no,
            'money' => $money,
            'msg' => '渠道商佣金',
            'type' => 'channel',
            'status' => '1',
            'source_user_id' => $order->user_id,
            'source_price' => $order->total_fee,
            'acct_id' => $order->acct_id
        ];
        self::create($data);
        $first = self::getChannel($channeluser->parent_id);
        if (!$first) {
            return;
        }
        $firstuser = User::get($first);
        if (!$firstuser || $firstuser['channel_level'] < 2) {
            return;
        }
        $commission_rate = db('user_channel')->where('id', $firstuser['channel_level'])->value('commission_rate');
        if ($commission_rate <= 0) {
            return;
        }
        $proportion = $commission_rate / 100;
        if ($proportion <= 0) {
            return;
        }
        $first_money = bcmul($order->total_fee - $order->only_fx_price, $proportion, 2);
        if ($first_money <= 0) {
            return;
        }
        $data = [
            'user_id' => $first,
            'order_no' => $order->order_no,
            'money' => $first_money,
            'msg' => '一级管理佣金',
            'type' => 'first',
            'status' => '1',
            'source_user_id' => $order->user_id,
            'source_price' => $order->total_fee - $order->only_fx_price,
            'acct_id' => $order->acct_id
        ];
        self::create($data);
        // $firstuser = User::get($first);
        // if (!$firstuser) {
        //     return;
        // }
        // $two = $firstuser->parent_id;
        // if (!$two) {
        //     return;
        // }

        // $two_rate = config('site.two') ?? 0;
        // if ($two_rate <= 0) {
        //     return;
        // }
        // $two_proportion = $two_rate / 100;
        // if ($two_proportion <= 0) {
        //     return;
        // }
        // $two_money = bcmul($order->total_fee - $order->only_fx_price, $two_proportion, 2);
        // if ($two_money <= 0) {
        //     return;
        // }
        // $data = [
        //     'user_id' => $two,
        //     'order_no' => $order->order_no,
        //     'money' => $two_money,
        //     'msg' => '二级管理佣金',
        //     'type' => 'two',
        //     'status' => '1',
        //     'source_user_id' => $order->user_id,
        //     'source_price' => $order->total_fee - $order->only_fx_price,
        //     'acct_id' => $order->acct_id
        // ];
        // self::create($data);
    }



    /**
     * 渠道商直推渠道商佣金(弃用)
     */
    public static function pushChannelCommission($order)
    {
        $user = User::get($order->user_id);
        if ($user->is_channel == 0) {
            return;
        }
        $channel_id = self::getChannel($user->parent_id);
        if (!$channel_id) {
            return;
        }
        $push_channel_commission = config('site.push_channel_commission');
        if ($push_channel_commission <= 0) {
            return;
        }
        $channel = $push_channel_commission / 100;
        if ($channel <= 0) {
            return;
        }
        $money = bcmul($order->total_fee, $channel, 2);
        if ($money <= 0) {
            return;
        }
        $data = [
            'user_id' => $channel_id,
            'order_no' => $order->order_no,
            'money' => $money,
            'msg' => '渠道商直推渠道商佣金',
            'type' => 'channel',
            'status' => '1',
            'source_user_id' => $order->user_id,
            'source_price' => $order->total_fee,
            'acct_id' => $order->acct_id
        ];
        self::create($data);
    }
    static function getChannel($pid)
    {
        $user = User::get($pid);
        if (!$user) {
            return false;
        }
        if ($user->is_channel) {
            return $user->id;
        }
        if ($user->parent_id) {
            return self::getChannel($user->parent_id);
        } else {
            return false;
        }
    }


    /**
     * 服务商佣金结算
     * @Author xy
     * @Date 2024-07-05 11:09:39
     * @LastEditors xy
     * @LastEditTime Do not edit
     * @Description 
     * @param {*} $order
     */
    public static function addAgentCommission($order)
    {

        $citys = explode('/', $order->consign_address);
        $province = self::getArea($citys['0'] ?? '', 0);
        $dev_rate = 0;
        $city = self::getArea($citys['1'] ?? '', 1, $province->id ?? 0);
        if ($city) {
            $city_id = $city->id;
            // $has[$city->id] = ($has[$city->id] ?? 0) + $order->total_fee;
            $user = User::where('is_agent', 1)->where('agent_area_id', $city->id)->field('id,agent_area_id,agent_area_ids,agent_rate')->find();
            if ($user) {
                $money = bcmul($order->total_fee - $order->only_fx_price, $user->agent_rate / 100, 2);
                $data = [
                    'user_id' => $user->id,
                    'order_no' => $order->order_no,
                    'money' => $money,
                    'msg' => '市级服务商佣金结算',
                    'type' => 'agent',
                    'status' => '1',
                    'source_user_id' => $order->user_id,
                    'source_price' => $order->total_fee,
                    'acct_id' => $order->acct_id
                ];


                self::create($data);
                $dev_rate = $user->agent_rate;
            }
        }


        if ($province) {
            //区域
            // $Areaid = $province->pid;
            // $has[$Areaid] = ($has[$Areaid] ?? 0) + $order->total_fee;
            // $has[$province->id] = ($has[$province->id] ?? 0) + $order->total_fee;
            // $province_id = $province->id;

            $puser = User::where('is_agent', 1)->where('agent_area_id', $province->id)->field('id,agent_area_id,agent_area_ids,agent_rate')->find();
            if ($puser) {
                $money = bcmul($order->total_fee - $order->only_fx_price, ($puser->agent_rate - $dev_rate) / 100, 2);
                $data = [
                    'user_id' => $puser->id,
                    'order_no' => $order->order_no,
                    'money' => $money,
                    'msg' => '省级服务商佣金结算',
                    'type' => 'agent',
                    'status' => '1',
                    'source_user_id' => $order->user_id,
                    'source_price' => $order->total_fee,
                    'acct_id' => $order->acct_id
                ];

                self::create($data);
            }
        }

        // $area = self::getArea($citys['2'] ?? '', 3, $city->id ?? 0);
        // if ($area) {
        //     $has[$area->id] = ($has[$area->id] ?? 0) + $order->total_fee;
        // }




    }


    /**
     * 获取区域ID
     * @Author xy
     * @Date 2023-07-27 10:51:06
     * @LastEditors xy
     * @LastEditTime Do not edit
     * @Description 
     * @param {*} $name
     * @param {*} $level
     */
    public static function getArea($name, $level = 1, $pid = 0)
    {
        if ($pid) {
            if ($name == '市中区') {
                $province = Area::where('name', $name)->where('level', $level)->where('pid', $pid)->find();
            } else {
                $province = Area::where('shortname', 'like', str_replace(['省', '市', '自治区', '特别行政区', '区', '县'], '', $name) . '%')->where('level', $level)->where('pid', $pid)->find();
            }
        } else {
            $province = Area::where('shortname', str_replace(['省', '市', '自治区', '特别行政区', '区', '县'], '', $name))->where('level', $level)->find();
        }
        return $province;
    }
}
